package com.gan.yidademo.controller.haikang;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gan.yidademo.common.util.HaiKangUtil;
import com.gan.yidademo.haikang.model.dto.event.FaceCaptureDto;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author gbw
 * @date 2023/10/12
 */
@RestController
@RequestMapping("/hk")
public class HaiKangController {

    private static final String IMG_URL_PREFIX = "https://112.53.191.202:1443/";

    /**
     * 接收人脸抓拍事件
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/face_snapshot", method = RequestMethod.POST, consumes = "application/json")
    public String receiveData(@RequestBody String data) {
        //格式化输出json
        JSONObject jsonObject = new JSONObject(data);

        // 美化输出到控制台，测试用
//        String prettyData = JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat,
//                SerializerFeature.WriteMapNullValue);
//        System.out.println(prettyData);

        JSONObject params = jsonObject.getJSONObject("params");
        JSONArray events = params.getJSONArray("events");
        JSONObject event = (JSONObject) events.get(0);
        // 时间发生时间
        String happenTime = event.getStr("happenTime");
        // 抓拍到的机器名称
        String srcName = event.getStr("srcName");
        FaceCaptureDto faceCaptureDto = new FaceCaptureDto();
        JSONObject eventData = event.getJSONObject("data");
        // 人员编号
        String personId = eventData.getStr("ExtEventPersonNo");
        // 抓拍照片
        JSONObject picInfo = eventData.getJSONObject("ExtTemp");
        String picUri = IMG_URL_PREFIX + picInfo.getStr("pic");
        // 下载图片到本地-测试用；实际使用的时候可以加上姓名.jpg，只能在内网中使用
        File imgSourceFile = new File("C:\\Users\\MrGods\\Desktop\\project\\舟山绿城\\海康威视\\抓拍信息\\123.jpg");
        if (!imgSourceFile.exists()) {
            try {
                imgSourceFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        HttpUtil.downloadFile(picUri, imgSourceFile);

        // todo 通过personId从数据库中和拿到人员姓名
        // faceCaptureDto.setName();
        faceCaptureDto.setSrcName(srcName);
        faceCaptureDto.setSnapPhotoUrl(picUri);
        faceCaptureDto.setPersonId(personId);
        faceCaptureDto.setHappenTime(happenTime);
        // 保存到数据库并转发照片给响应的人

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("code", "0");
        jsonBody.put("msg", "success");
        jsonBody.put("data", null);
        return jsonBody.toString();
    }
}
